package com.store.bookstore_backend.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.store.bookstore_backend.Util.OrderUtil;
import com.store.bookstore_backend.config.AlipayConfig;
import com.store.bookstore_backend.domain.*;
import com.store.bookstore_backend.dto.*;
import com.store.bookstore_backend.mapper.*;
import com.store.bookstore_backend.service.BookstoreOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class BookstoreOrderServiceImpl implements BookstoreOrderService {
    @Autowired
    BookstoreOrderMapper bookstoreOrderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    BookMapper bookMapper;
    @Autowired
    ShopcarMapper shopcarMapper;
    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public List<OrderDTO> getOrders(HttpServletRequest request) {
        List<OrderDTO> orderDTOs = new ArrayList<>();

        Long userId = (Long) request.getAttribute("userId");
        ;
        List<BookstoreOrder> bookstoreOrders = bookstoreOrderMapper.selectByUserId(userId);
        for (BookstoreOrder bookstoreOrder : bookstoreOrders) {
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setCreateDate(bookstoreOrder.getCreateDate());
            orderDTO.setStatus(bookstoreOrder.getStatus());
            orderDTO.setReceiveAddress(bookstoreOrder.getReceiveAddress());
            orderDTO.setReceivePhone(bookstoreOrder.getReceivePhone());
            orderDTO.setReceiveUsername(bookstoreOrder.getReceiveUsername());
            orderDTO.setOrderId(bookstoreOrder.getId());
            User user = userMapper.getUserById(userId);
            orderDTO.setUsername(user.getUsername());
            orderDTOs.add(orderDTO);
            List<OrderItem> orderItems = orderItemMapper.getOrderItemByOrderId(bookstoreOrder.getId());
            BigDecimal totalPrice = BigDecimal.ZERO;
            Integer totalNum = 0;
            for (OrderItem orderItem : orderItems) {
                System.out.println(orderItem);
                if (orderItem != null) {
                    totalNum = totalNum + orderItem.getNum();
                    Book book = bookMapper.selectBookById(orderItem.getBookId());
                    BigDecimal price = BigDecimal.valueOf(book.getPrice());
                    totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(orderItem.getNum())));
                }
            }
            orderDTO.setTotalPrice(totalPrice.add(BigDecimal.valueOf(10)));
            orderDTO.setTotalNum(totalNum);
        }
        return orderDTOs;
    }

    @Override
    public OrderInfoDTO getOrderById(HttpServletRequest request, String orderId) {
        OrderInfoDTO orderInfoDTO = new OrderInfoDTO();
        List<OrderItem> orderItems = orderItemMapper.getOrderItemByOrderId(orderId);
        List<OrderItemDTO> orderItemDTOS = new ArrayList<>();
        BigDecimal totalsPrice = BigDecimal.ZERO;
        for (OrderItem orderItem : orderItems) {
            OrderItemDTO orderItemDTO = new OrderItemDTO();
            orderItemDTO.setNum(orderItem.getNum());
            Book book = bookMapper.selectBookById(orderItem.getBookId());
            orderItemDTO.setName(book.getName());
            orderItemDTO.setCover(book.getCover());
            BigDecimal price = BigDecimal.valueOf(book.getPrice());
            orderItemDTO.setPrice(price);
            BigDecimal totalPrice = price.multiply(BigDecimal.valueOf(orderItem.getNum()));
            orderItemDTO.setTotalPrice(totalPrice);
            totalsPrice = totalsPrice.add(totalPrice);
            orderItemDTOS.add(orderItemDTO);
        }
        orderInfoDTO.setOrderItems(orderItemDTOS);
        orderInfoDTO.setOrderId(orderId);
        BookstoreOrder bookstoreOrder = bookstoreOrderMapper.selectByOrderId(orderId);
        orderInfoDTO.setCreateDate(bookstoreOrder.getCreateDate());
        orderInfoDTO.setStatus(bookstoreOrder.getStatus());
        orderInfoDTO.setReceiveAddress(bookstoreOrder.getReceiveAddress());
        orderInfoDTO.setReceivePhone(bookstoreOrder.getReceivePhone());
        orderInfoDTO.setReceiveUsername(bookstoreOrder.getReceiveUsername());
        orderInfoDTO.setTotalPrice(totalsPrice.add(BigDecimal.valueOf(10)));
        orderInfoDTO.setTotalNum(orderItems.size());
        return orderInfoDTO;
    }

    @Override
    public OrderInfoDTO createOrder(HttpServletRequest request, CreateOrderDTO createOrderDTO) {
        Long userId = (Long) request.getAttribute("userId");
        BookstoreOrder bookstoreOrder = new BookstoreOrder();
        bookstoreOrder.setCreateDate(LocalDateTime.now());
        bookstoreOrder.setUserId(userId);
        bookstoreOrder.setPayWay("支付宝");
        bookstoreOrder.setTrackingNumber(null);
        bookstoreOrder.setDistributionMode(null);
        bookstoreOrder.setStatus(1);
        bookstoreOrder.setPayDate(null);
        bookstoreOrder.setReceiveUsername(createOrderDTO.getReceiveUsername());
        bookstoreOrder.setReceivePhone(createOrderDTO.getReceivePhone());
        bookstoreOrder.setReceiveAddress(createOrderDTO.getReceiveAddress());
        bookstoreOrder.setId(OrderUtil.generateOrderId());
        bookstoreOrderMapper.insert(bookstoreOrder);
        List<Integer> shopCarIds = createOrderDTO.getShopCarIds();
        for (Integer shopCarId : shopCarIds) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(bookstoreOrder.getId());
            Shopcar shopcar = shopcarMapper.selectShopcarById(shopCarId);
            orderItem.setBookId(shopcar.getBookId());
            orderItem.setNum(shopcar.getNum());
            orderItemMapper.InsertOrderItem(orderItem);
        }
        return getOrderById(request, bookstoreOrder.getId());
    }

    @Override
    public void closeOrder(HttpServletRequest request, String orderId) {
        orderItemMapper.DeleteOrderItemByOrderId(orderId);
        bookstoreOrderMapper.deleteByOrderId(orderId);
    }

    @Override
    public String payOrder(HttpServletRequest request, PayOrderDTO payOrderDTO) {
        // 创建AlipayClient实例
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),
                "json",
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()
        );
//        System.out.println(alipayConfig.getGatewayUrl()+"\n"+alipayConfig.getAppId()+"\n"+alipayConfig.getCharset()+"\n"+alipayConfig.getSignType()+"\n"+alipayConfig.getPrivateKey()+alipayConfig.getAlipayPublicKey());
//        System.out.println("alipayClient Create Success");
        // 创建AlipayTradePagePayRequest实例
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//        alipayRequest.setReturnUrl(payOrderDTO.getPathUrl());
//        System.out.println("alipayRequest Create Success");
        // 设置业务参数
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setOutTradeNo(payOrderDTO.getOrderId()); // 您应动态生成唯一订单号
        OrderInfoDTO orderInfoDTO = getOrderById(request, payOrderDTO.getOrderId());
        model.setTotalAmount(String.valueOf(orderInfoDTO.getTotalPrice())); // 动态获取订单金额
        StringBuilder subject = new StringBuilder();
        for (OrderItemDTO orderItem : orderInfoDTO.getOrderItems()) {
            subject.append(orderItem.getName());
            subject.append(",");
        }
        model.setSubject(subject.toString());
        model.setBody(System.currentTimeMillis() + "");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
//        model.setTimeoutExpress(LocalDate.);
//        System.out.println(LocalDate.now());
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();

        // 向后推十分钟
        LocalDateTime tenMinutesLater = now.plusMinutes(10);

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        model.setTimeExpire(tenMinutesLater.format(formatter));

        alipayRequest.setBizModel(model);

        alipayRequest.setReturnUrl(payOrderDTO.getPathUrl());

        String result = "";
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }

    @Override
    public void paySuccess(PaySuccessDTO paySuccessDTO) {
        BookstoreOrder bookstoreOrder = new BookstoreOrder();
        bookstoreOrder.setPayDate(paySuccessDTO.getPayDate());
        bookstoreOrder.setId(paySuccessDTO.getOrderId());
        bookstoreOrder.setPayWay(paySuccessDTO.getPayWay());
        bookstoreOrder.setStatus(3);
        bookstoreOrderMapper.update(bookstoreOrder);
    }

    @Override
    public void orderComplete(String orderId) {
        BookstoreOrder bookstoreOrder = new BookstoreOrder();
        bookstoreOrder.setId(orderId);
        bookstoreOrder.setStatus(4);
        bookstoreOrderMapper.update(bookstoreOrder);
    }

}
